﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class InfinityMountain : MonoBehaviour
{
    //单个山脉背景prefab
    [SerializeField]
    private GameObject mountain;

    //山脉列表
    [SerializeField]
    private List<GameObject> mountains;

    //移动速度
    [SerializeField]
    private float moveSpeed;

    // Start is called before the first frame update
    void Start()
    {
        //创建山脉填充现有的背景
        RectTransform parentCanvas = GetComponentInParent<RectTransform>();
        float localScreenWidth = Screen.width / parentCanvas.lossyScale.x;
        float localScreenHeight = Screen.height / parentCanvas.lossyScale.y;

        RectTransform rectTransform = mountain.GetComponent<RectTransform>();

        transform.localPosition = new Vector3(rectTransform.sizeDelta.x / 2 - localScreenWidth / 2, rectTransform.sizeDelta.y / 2 - localScreenHeight / 2);

        int mountainNum = (int)Math.Ceiling(localScreenWidth / rectTransform.sizeDelta.x);

        for(int i = 0; i<=mountainNum; i++)
        {
            GameObject instanceMountain = Instantiate(mountain, transform.position,Quaternion.identity,transform.parent);
            mountains.Add(instanceMountain);
            transform.localPosition += new Vector3(rectTransform.sizeDelta.x, 0);

        }
    }

    // Update is called once per frame
    void Update()
    {
        //让背景山脉移动，并创建新山脉，销毁旧山脉
        foreach(GameObject mountain in mountains)
        {
            mountain.transform.localPosition += new Vector3(-moveSpeed * Time.deltaTime, 0);
        }
        if (OutScreen(mountains[0]))
        {
            RectTransform rectTransform = mountain.GetComponent<RectTransform>();
            GameObject lastMountain = mountains[mountains.Count - 1];
            transform.localPosition = lastMountain.transform.localPosition + new Vector3(rectTransform.sizeDelta.x, 0);
            GameObject instanceMountain = Instantiate(mountain, transform.position, Quaternion.identity, transform.parent);
            mountains.Add(instanceMountain);

            Destroy(mountains[0]);
            mountains.RemoveAt(0);
        }
    }

    bool OutScreen(GameObject gameObject)
    {
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();
        RectTransform parentCanvas = GetComponentInParent<RectTransform>();
        float localScreenWidth = Screen.width / parentCanvas.lossyScale.x;

        if(Mathf.Abs(rectTransform.localPosition.x) - rectTransform.sizeDelta.x/2 > localScreenWidth / 2)
        {
            return true;
        }
        return false;
    }
}
